package com.ynr.bank.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Random;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.ynr.bank.service.IBankService;
import com.ynr.voucher.service.IVoucherBankService;

@Service
public class BankServiceImpl implements IBankService {

	public static final Logger logger = LoggerFactory.getLogger(BankServiceImpl.class);
	
	@Autowired
	private IVoucherBankService voucherBankService;
	
	@Override
	public void uploadBankStatement(String billDate, int companyId, String rootPath, MultipartFile multifile, String bankType) {
		String filePath = rootPath + "/" + getGernarateFileName(multifile);
		try {
			FileUtils.copyInputStreamToFile(multifile.getInputStream(),
					new File(filePath));
		} catch (IOException e) {
			logger.error("InvoiceServiceImpl uploadInvoice method create file error : {}", e.toString());
		}
		voucherBankService.processBankStatement(filePath, companyId, bankType, billDate);
	}

	private String getGernarateFileName(MultipartFile file) {
		Random rdm = new Random(System.currentTimeMillis());
		String extendName = file.getOriginalFilename().substring(
				file.getOriginalFilename().lastIndexOf(".") + 1);
		return System.currentTimeMillis() + Math.abs(rdm.nextInt())
				% 1000 + (extendName == null ? ".unknown" : "." + extendName);
	}

	
}
